﻿// 1.1.3.16. Write a program that exchanges bits {p, p+1, …, p+k-1) with bits {q, q+1, …, q+k-1} of given 32-bit unsigned integer.

using System;

class ExchangingBitsInAnySequence
{
    static void Main()
    {
        Console.Write("Please enter integer number as I suggest you \"4294901760\": ");
        uint number = uint.Parse(Console.ReadLine());
        Console.Write("Please enter from which bit you want to exchange the first sequence of bits: ");
        byte fromBitFirst = byte.Parse(Console.ReadLine());
        Console.Write("Please enter from which bit you want to exchange the second sequence of bits: ");
        byte fromBitSecond = byte.Parse(Console.ReadLine());
        Console.Write("Please enter the length of sequences you want to exchange: ");
        byte amountBits = byte.Parse(Console.ReadLine());
        bool[] valuesFirstSequence = new bool[amountBits];
        bool[] valuesSecondSequence = new bool[amountBits];

        Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));

        if (fromBitFirst > fromBitSecond)
        {
            fromBitFirst = (byte)(fromBitFirst + fromBitSecond);
            fromBitSecond = (byte)(fromBitFirst - fromBitSecond);
            fromBitFirst = (byte)(fromBitFirst - fromBitSecond);
        }

        for (int i = 0; i < amountBits; i++)
        {
            valuesFirstSequence[i] = ((number >> (fromBitFirst + i)) & 1) == 1;
        }
        for (int i = 0; i < amountBits; i++)
        {
            valuesSecondSequence[i] = ((number >> (fromBitSecond + i)) & 1) == 1;
        }

        for (int i = 0; i < amountBits; i++)
        {
            if (valuesFirstSequence[i] == true)
            {
                number = number | (1u << (fromBitSecond + i));
            }
            else
            {
                number = number & (~(1u << (fromBitSecond + i)));
            }
        }
        for (int i = 0; i < amountBits; i++)
        {
            if (valuesSecondSequence[i] == true)
            {
                number = number | (1u << (fromBitFirst + i));
            }
            else
            {
                number = number & (~(1u << (fromBitFirst + i)));
            }
        }
        Console.WriteLine(Convert.ToString(number, 2).PadLeft(32, '0'));
    }
}